package com.Cychat.commons.utils;



import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.UUID;

public class JWTUtil {
    public static final String SECRET_KEY = "Cychat123"; //秘钥
    public static final long TOKEN_EXPIRE_TIME =  30 * 60 * 1000L; //token过期时间(毫秒)
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 15 * 24 * 3600 * 1000L; //refreshToken过期时间(毫秒)
    private static final String ISSUER = "Esan"; //签发人

    /**
     * 生成签名 （token）
     */
    public static String generateToken(long uid){
        Date now = new Date();
        //创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法

        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now)  //签发时间
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("uid", uid) //保存身份标识
                .withJWTId(UUID.randomUUID().toString()) //添加JWT ID
                .sign(algorithm);
        return token;
    }
    /**
     * 生成reflashtoekn（retoken）
     */
    public static String generateRefreshToken(Long uid) {
        Date now = new Date();
        //创建签名算法对象
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法

        String token = JWT.create()
                .withIssuer(ISSUER) //签发人
                .withIssuedAt(now)  //签发时间
                .withExpiresAt(new Date(now.getTime() + REFRESH_TOKEN_EXPIRE_TIME)) //过期时间
                .withClaim("uid", uid) //保存身份标识
                .withJWTId(UUID.randomUUID().toString()) //添加JWT ID
                .sign(algorithm);
        return token;
    }
    /**
     * 验证token
     */
    public static TokenEnum verify(String token){
        try {
            //签名算法
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build();
            verifier.verify(token);
            return TokenEnum.TOKEN_SUCCESS;
        } catch (TokenExpiredException ex){
            return TokenEnum.TOKEN_EXPIRE;
            //ex.printStackTrace();
        } catch (Exception e) {
            return TokenEnum.TOKEN_BAD;
        }
    }

    /**
     * 从token获取uid
     */
    public static Long getuid(String token){
        try{
            return JWT.decode(token).getClaim("uid").asLong();
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return 0L;
    }

    /**
     * 从token获取过期时间
     */
    public static Date getExpiration(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getExpiresAt();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 从token获取JWT ID
     */
    public static String getJti(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getId();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 测试方法：打印JWT的所有声明
     */
    public static void printAllClaims(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            System.out.println("JWT Claims:");
            System.out.println("  Issuer: " + jwt.getIssuer());
            System.out.println("  Issued At: " + jwt.getIssuedAt());
            System.out.println("  Expires At: " + jwt.getExpiresAt());
            System.out.println("  ID (jti): " + jwt.getId());
            System.out.println("  Subject: " + jwt.getSubject());
            System.out.println("  Claims: " + jwt.getClaims());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
